package com.swift.client.udp;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;

/**
 * @author zl
 * @version 1.0
 * @date 2021/9/28 11:36
 */
@Component
@Slf4j
public class UdpClient3 {

    private Channel channel;

    private EventLoopGroup group ;

    private class CLientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
            String body = packet.content().toString(CharsetUtil.UTF_8);
            System.out.println(body);
        }
    }

    @PostConstruct
    private void startClient3() {
        new Thread(()->{
            log.info("启动client3");
            group = new NioEventLoopGroup();
            try {
                Bootstrap b = new Bootstrap();
                b.group(group)
                        .channel(NioDatagramChannel.class)
                        .option(ChannelOption.SO_BROADCAST,true)
                        .option(ChannelOption.SO_RCVBUF, 2048 * 1024)// 设置UDP读缓冲区为2M
                        .option(ChannelOption.SO_SNDBUF, 1024 * 1024)// 设置UDP写缓冲区为1M
                        .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) // 线程池复用缓冲区
                        .handler(new ChannelInitializer<NioDatagramChannel>() {
                            //NioDatagramChannel标志着是UDP格式的
                            @Override
                            protected void initChannel(NioDatagramChannel ch)
                                    throws Exception {
                                // TODO Auto-generated method stub
                                //创建一个执行Handler的容器
                                ChannelPipeline pipeline = ch.pipeline();
                                pipeline.addLast(new StringDecoder());
                                pipeline.addLast(new StringEncoder());
                                //执行具体的处理器
                                pipeline.addLast("handler", new CLientHandler());//消息处理器
                            }

                        });

                channel = b.bind(8888).sync().channel();
                channel.writeAndFlush(new DatagramPacket(
                        Unpooled.copiedBuffer("服务器你好！", CharsetUtil.UTF_8),
                        //地址
                        new InetSocketAddress(
                                "118.190.147.24", 40008
                        )));
                channel.closeFuture().await();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                group.shutdownGracefully();
            }
        }).start();
    }

    public void sendMessage(String ip,Integer port,String messsage) throws InterruptedException {
        channel.writeAndFlush(new DatagramPacket(
                Unpooled.copiedBuffer(messsage, CharsetUtil.UTF_8),
                new InetSocketAddress(ip, port)));
    }




}
